package com.czkt.springboot_mybatis_test.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czkt.springboot_mybatis_test.entity.Page;
import com.czkt.springboot_mybatis_test.entity.SysRole;
import com.czkt.springboot_mybatis_test.entity.SysUser;
import com.czkt.springboot_mybatis_test.entity.vo.UserRole;
import com.czkt.springboot_mybatis_test.service.ISysRoleService;
import com.czkt.springboot_mybatis_test.service.ISysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2024-06-18
 */
@Controller
@RequestMapping("/springboot_mybatis_test/sys-user")
public class SysUserController {
    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/doLogin")
    public String doLogin(String usrName, String usrPassword,Boolean likeMe, HttpSession session, Model model){
//        UserRole user = userService.selectSysUser(usrName, usrPassword);
//        if (user != null){
//            session.setAttribute("loginUser",user);
//            if (likeMe!=null){
//                stringRedisTemplate.opsForValue().set("loginUser", JSON.toJSONString(user));
//            }
//            return "main";
//        }else{
//            model.addAttribute("message","账号或密码错误");
//            return "login";
//        }
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(usrName,usrPassword);
        try {
            SecurityUtils.getSubject().login(usernamePasswordToken);
            UserRole userRole = (UserRole) SecurityUtils.getSubject().getPrincipal();
            session.setAttribute("loginUser",userRole);
        }catch (UnknownAccountException e){
            model.addAttribute("message","账号不存在!");
            return "login";
        }catch (LockedAccountException e){
            model.addAttribute("message","账号被禁用!");
            return "login";
        }catch (AuthenticationException e){
            model.addAttribute("message","账号或密码错误");
            return "login";
        }
        return "main";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginUser");
        return "login";
    }

    @RequestMapping("/crm/user/list")
    public String userList(String usrName,String usrRoleId,Integer pageIndex,Model model){
        List<SysRole> role = roleService.list();
        if(pageIndex == null){
            pageIndex = 1;
        }
        Page page = new Page();
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if(usrName != null && !usrName.equals("")){
            queryWrapper.eq("usr_name",usrName);
        }
        if (usrRoleId != null && !usrRoleId.equals("0")){
            queryWrapper.eq("usr_role_id",usrRoleId);
        }
        int count = userService.count(queryWrapper);
        if(count == 0){
            count = 1;
        }
        page.setTotalCount(count);
        if(pageIndex < 1){
            pageIndex = 1;
        }
        if(pageIndex > page.getTotalPageCount()){
            pageIndex = page.getTotalPageCount();
        }
        int index = (pageIndex - 1) * page.getPageSize();
        page.setPageNo(pageIndex);
        if(usrName == null){
            usrName = "";
        }
        if (usrRoleId == null || usrRoleId.equals("0")){
            usrRoleId = "";
        }
        page.setSysRoleList(userService.selectSysUserAndRole(usrName,usrRoleId,index,page.getPageSize()));
        model.addAttribute("roles",role);
        model.addAttribute("usrRoleId",usrRoleId);
        model.addAttribute("usrName",usrName);
        model.addAttribute("userPager",page);
        return "/user/list";
    }

    @RequestMapping("/user/edit")
    public String update(String usrId,Model model){
        List<SysRole> role = roleService.list();
        UserRole userRole = userService.selectUsrId(usrId);
        model.addAttribute("user",userRole);
        model.addAttribute("roles",role);
        return "/user/edit";
    }

    @RequestMapping("/user/save")
    public String toUpdate(SysUser sysUser){
        userService.toUpdateUser(sysUser);
        return "redirect:/springboot_mybatis_test/sys-user/crm/user/list";
    }

    @RequestMapping("/crm/user/del/{usrId}")
    @ResponseBody
    public Object deleteSysUser(@PathVariable("usrId") String usrId){
        userService.deleteByUsrId(usrId);
        Map<String,Object> map = new HashMap<>();
        map.put("delResult","true");
        return map;
    }

    @RequestMapping("/user/add")
    public String insertUser(Model model){
        List<SysRole> role = roleService.list();
        model.addAttribute("roles",role);
        return "/user/add";
    }

    @RequestMapping("/user/insert")
    public String toInsertUser(SysUser sysUser){
        userService.toInsertUser(sysUser);
        return "redirect:/springboot_mybatis_test/sys-user/crm/user/list";
    }
}
